import React, { memo, useEffect, useCallback } from 'react';
import { Modal, Form, Input, Select, Button, Space, message } from 'antd';
import { UserOutlined, IdcardOutlined, PhoneOutlined, EditOutlined } from '@ant-design/icons';
import type { IStudentFormProps } from '@/types/components/student';
import type { IStudentCreateRequest, IStudentUpdateRequest } from '@/types/student';
import { StudentStatusEnum } from '@/types/student';
import { validateStudentData } from '@/utils/validation';
import styles from './StudentForm.module.css';

const { Option } = Select;
const { TextArea } = Input;

/**
 * 学生表单组件
 * @description 用于创建和编辑学生信息的表单组件
 */
const StudentForm: React.FC<IStudentFormProps> = memo(({
  student,
  visible,
  mode,
  onSubmit,
  onCancel,
  loading = false
}) => {
  const [form] = Form.useForm();

  // 表单初始化
  useEffect(() => {
    if (visible) {
      if (mode === 'edit' && student) {
        // 编辑模式，填充现有数据
        form.setFieldsValue({
          name: student.name,
          studentId: student.studentId,
          grade: student.grade,
          class: student.class,
          phone: student.phone,
          remark: student.remark,
          status: student.status
        });
      } else {
        // 创建模式，重置表单
        form.resetFields();
        form.setFieldsValue({
          status: StudentStatusEnum.ACTIVE // 默认状态为在读
        });
      }
    }
  }, [visible, mode, student, form]);

  // 处理表单提交
  const handleSubmit = useCallback(async () => {
    try {
      const values = await form.validateFields();
      
      // 数据验证
      const validationResult = validateStudentData(values);
      if (!validationResult.isValid) {
        message.error(validationResult.message);
        return;
      }

      // 构造提交数据
      const submitData: IStudentCreateRequest | IStudentUpdateRequest = {
        name: values.name.trim(),
        studentId: values.studentId.trim(),
        grade: values.grade?.trim() || undefined,
        class: values.class?.trim() || undefined,
        phone: values.phone?.trim() || undefined,
        remark: values.remark?.trim() || undefined,
        status: values.status
      };

      await onSubmit(submitData);
      form.resetFields();
    } catch (error) {
      console.error('表单提交失败:', error);
      if (error instanceof Error) {
        message.error(error.message);
      }
    }
  }, [form, onSubmit]);

  // 处理取消操作
  const handleCancel = useCallback(() => {
    form.resetFields();
    onCancel();
  }, [form, onCancel]);

  // 学号验证规则
  const validateStudentId = useCallback(async (_: any, value: string) => {
    if (!value) {
      throw new Error('请输入学号');
    }
    if (value.length < 3) {
      throw new Error('学号长度不能少于3位');
    }
    if (!/^[A-Za-z0-9]+$/.test(value)) {
      throw new Error('学号只能包含字母和数字');
    }
  }, []);

  // 手机号验证规则
  const validatePhone = useCallback(async (_: any, value: string) => {
    if (value && !/^1[3-9]\d{9}$/.test(value)) {
      throw new Error('请输入正确的手机号码');
    }
  }, []);

  return (
    <Modal
      title={
        <div className={styles.modalTitle}>
          <EditOutlined className={styles.titleIcon} />
          {mode === 'create' ? '添加学生' : '编辑学生'}
        </div>
      }
      open={visible}
      onCancel={handleCancel}
      footer={
        <Space>
          <Button onClick={handleCancel}>
            取消
          </Button>
          <Button
            type="primary"
            loading={loading}
            onClick={handleSubmit}
          >
            {mode === 'create' ? '添加' : '保存'}
          </Button>
        </Space>
      }
      width={520}
      destroyOnHidden
      className={styles.studentFormModal}
    >
      <Form
        form={form}
        layout="vertical"
        className={styles.studentForm}
        autoComplete="off"
      >
        <Form.Item
          name="name"
          label="学生姓名"
          rules={[
            { required: true, message: '请输入学生姓名' },
            { min: 2, message: '姓名长度不能少于2个字符' },
            { max: 20, message: '姓名长度不能超过20个字符' }
          ]}
        >
          <Input
            prefix={<UserOutlined />}
            placeholder="请输入学生姓名"
            maxLength={20}
            showCount
          />
        </Form.Item>

        <Form.Item
          name="studentId"
          label="学号"
          rules={[
            { required: true, message: '请输入学号' },
            { validator: validateStudentId }
          ]}
        >
          <Input
            prefix={<IdcardOutlined />}
            placeholder="请输入学号"
            maxLength={20}
            showCount
          />
        </Form.Item>

        <div className={styles.formRow}>
          <Form.Item
            name="grade"
            label="年级"
            className={styles.halfWidth}
          >
            <Select placeholder="请选择年级" allowClear>
              <Option value="一年级">一年级</Option>
              <Option value="二年级">二年级</Option>
              <Option value="三年级">三年级</Option>
              <Option value="四年级">四年级</Option>
              <Option value="五年级">五年级</Option>
              <Option value="六年级">六年级</Option>
              <Option value="初一">初一</Option>
              <Option value="初二">初二</Option>
              <Option value="初三">初三</Option>
              <Option value="高一">高一</Option>
              <Option value="高二">高二</Option>
              <Option value="高三">高三</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="class"
            label="班级"
            className={styles.halfWidth}
          >
            <Input
              placeholder="请输入班级"
              maxLength={20}
            />
          </Form.Item>
        </div>

        <Form.Item
          name="phone"
          label="联系电话"
          rules={[
            { validator: validatePhone }
          ]}
        >
          <Input
            prefix={<PhoneOutlined />}
            placeholder="请输入联系电话"
            maxLength={11}
          />
        </Form.Item>

        <Form.Item
          name="status"
          label="状态"
          rules={[{ required: true, message: '请选择状态' }]}
        >
          <Select placeholder="请选择状态">
            <Option value={StudentStatusEnum.ACTIVE}>在读</Option>
            <Option value={StudentStatusEnum.INACTIVE}>休学</Option>
            <Option value={StudentStatusEnum.GRADUATED}>毕业</Option>
          </Select>
        </Form.Item>

        <Form.Item
          name="remark"
          label="备注"
        >
          <TextArea
            placeholder="请输入备注信息"
            rows={3}
            maxLength={200}
            showCount
          />
        </Form.Item>
      </Form>
    </Modal>
  );
});

StudentForm.displayName = 'StudentForm';

export default StudentForm;